package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryUserByBlog(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("数据不存在");
        }
        queryUserByBlog(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户是否点赞过该博客
        String key = "blog:liked:" + id;
        Double success = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (success == null) {
            //4.没有点赞，则点赞

            // LambdaUpdateWrapper<Blog> updateWrapper=new LambdaUpdateWrapper<>();
            // updateWrapper.eq(Blog::getId,id);
            // updateWrapper.setSql("liked=liked+1");

            //数据库中点赞数加一
            boolean update = update().setSql("liked=liked+1").eq("id", id).update();
            if (update) {
                //redis中保存当前用户id
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //3.点赞过，则取消点赞
            //3.1 redis中remove当前用户id
            boolean update = update().setSql("liked=liked-1").eq("id", id).update();
            if (update) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = "blog:liked:" + id;
        //查到了前5个用户的id
        Set<String> redis = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (redis == null || redis.isEmpty()) {
            return Result.ok();
        }
        List<UserDTO> result = redis.stream().map(item -> {
            UserDTO userDTO = new UserDTO();
            User user = userService.getById(Long.valueOf(item));
            BeanUtil.copyProperties(user, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        return Result.ok(result);
    }

    /**
     * 博主使用推模式将发布的博客推送到用户的收件箱中
     *
     * @param blog
     * @return
     */
    @Override
    public Object saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        // 查询用户的所有粉丝

        //使用feed流timeline模式下的推模式
        List<Follow> followres = followService.list(new LambdaQueryWrapper<Follow>().eq(Follow::getFollowUserId, user.getId()));
        followres.stream().map(follow -> {
            Long userId = follow.getUserId();
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            return null;
        });
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 用户使用滚动查询获取关注的人推送到收件箱中的博客
     *
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, max, 0, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //获取上一次滚动查询的最小时间
        Long minTime = 0L;
        //获取上一次查询时最小时间有几个，作为下一次滚动查询的偏移量offset
        int os=1;
        List<Long> ids=new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time=typedTuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else{
                minTime=time;
                os=1;
            }
        }
        String idStr= StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by filed (id," + idStr + ")").list();

        blogs.stream().map(blog -> {
            queryUserByBlog(blog);
            isBlogLiked(blog);
            return null;
        });

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }


    private void queryUserByBlog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        Long userId = user.getId();
        String key = "blog:liked:" + blog.getId();
        Double success = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(success != null);
    }
}
